package com.onlyphoto.onlymall.mvp.view.activity

import android.content.Context
import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.gson.Gson
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.base.BaseActivity
import com.onlyphoto.onlymall.bean.request.GoodsCondition
import com.onlyphoto.onlymall.bean.response.GoodsBean
import com.onlyphoto.onlymall.bean.response.SearchBean
import com.onlyphoto.onlymall.mvp.contract.CSearch
import com.onlyphoto.onlymall.mvp.presenter.PSearchImpl
import com.onlyphoto.onlymall.mvp.view.adapter.SearchAdapter
import com.onlyphoto.onlymall.mvp.view.binder.SearchBinder
import com.onlyphoto.onlymall.utils.SharePreferenceUtil
import kotlinx.android.synthetic.main.activity_search.*
import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter
import org.json.JSONArray


class SearchActivity : BaseActivity<PSearchImpl>(), CSearch.IVSearch, View.OnClickListener{

    var hotAdapter: SearchAdapter? = null
    private var historyAdapter: SearchAdapter? = null
    private var flexBoxLayoutManager: FlexboxLayoutManager? = null
    private var historyLayoutManager: FlexboxLayoutManager? = null
    var list = arrayListOf<SearchBean>()
    private val historyList = ArrayList<String>()

    private var searchResultAdapter: MultiTypeAdapter? = null
    var items: Items? = null
    var layoutManager: LinearLayoutManager? = null
    var jsonData = ""
    var content: String? = ""

    override fun retry() {}

    override fun loadData() {
        //加载数据
        mPresenter?.getTopSearch()
    }

    override fun init() {
        content = intent.getStringExtra("content")
        et_search.setText(content)
        if (content != null) {
            et_search.setSelection(content?.length!!)
        }
        initRv()
        et_search.requestFocus()
    }

    private fun initRv() {
        hotAdapter = SearchAdapter()
        historyAdapter = SearchAdapter()
        flexBoxLayoutManager = FlexboxLayoutManager(this)
        historyLayoutManager = FlexboxLayoutManager(this)
        rv_hot.adapter = hotAdapter
        rv_hot.layoutManager = flexBoxLayoutManager

        rv_history.adapter = historyAdapter
        rv_history.layoutManager = historyLayoutManager

        getHistory()

        searchResultAdapter = MultiTypeAdapter()
        items = Items()
        layoutManager = LinearLayoutManager(this)
        searchResultAdapter?.register(GoodsBean::class.java, SearchBinder())
        searchResultAdapter?.items = items!!
        rv_search_result.adapter = searchResultAdapter
        rv_search_result.layoutManager = layoutManager

    }

    private fun getHistory(){
        jsonData = SharePreferenceUtil.getInstance(this).getData("searchHistory")
        if (jsonData != "") {
            val jsonArray = JSONArray(jsonData)
            for (i in 0 until jsonArray.length()) {
                val words = jsonArray.get(i)
                historyList.add(words.toString())
            }
            cl_history.visibility = View.VISIBLE
            historyAdapter?.setItemData(historyList)
        }
    }

    override fun getTopSearchSuccess(list: ArrayList<String>) {
        hotAdapter?.setItemData(list)
    }

    override fun searchSuccess(list: ArrayList<GoodsBean>) {
        if (et_search.text.toString() != "") {
            items?.clear()
            rv_search_result.visibility = View.VISIBLE
            items?.addAll(list)
            hotAdapter?.notifyDataSetChanged()
        }
    }

    override fun initListener() {
        //点击事件初始化
        et_search.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH){
                et_search.clearFocus()
                val view = window.peekDecorView()
                if (view != null) {
                    val inputManger = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    inputManger.hideSoftInputFromWindow(view.windowToken, 0)
                }
                et_search.text.toString().let {
                    addToHistory(it)
                }
                startActivity(Intent(this, GoodsListActivity::class.java)
                        .putExtra("content", et_search.text.toString()))
                finish()
                return@OnEditorActionListener true
            }
            return@OnEditorActionListener false
        })

        et_search.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(s: Editable?) {
                if (s.toString() == "") {
                    rv_search_result.visibility = View.GONE
                } else {
                    search(s.toString())
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

        })

        delete_history.setOnClickListener(this)
        cancel.setOnClickListener(this)

        hotAdapter?.setOnItemClickListener(object :SearchAdapter.OnItemClickListener{
            override fun click(word: String) {
                et_search.setText(word)
                search(word)
                addToHistory(word)
                startActivity(Intent(this@SearchActivity, GoodsListActivity::class.java).putExtra("content", word))
                finish()
            }
        })

        historyAdapter?.setOnItemClickListener(object :SearchAdapter.OnItemClickListener{
            override fun click(word: String) {
                et_search.setText(word)
                search(word)
                addToHistory(word)
                startActivity(Intent(this@SearchActivity, GoodsListActivity::class.java).putExtra("content", word))
                finish()
            }
        })
    }

    fun search(word: String){
        val condition = GoodsCondition()
        condition.search_word = word
        mPresenter?.search(condition)
    }

    fun addToHistory(word: String){




        if (word != "") {
            if (!historyList.contains(word)) {
                if (historyList.size == 15) {
                    historyList.removeAt(historyList.size - 1)
                }
                historyList.add(0, word)
                cl_history.visibility = View.VISIBLE
            } else {
                historyList.removeAt(historyList.indexOf(word))
                historyList.add(0, word)
            }
            historyAdapter?.setItemData(historyList)
            SharePreferenceUtil.getInstance(this).setData("searchHistory", Gson().toJson(historyList))
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.delete_history -> {
                SharePreferenceUtil.getInstance(this).setData("searchHistory", "")
                historyList.clear()
                cl_history.visibility = View.GONE
            }
            R.id.cancel -> finish()
        }
    }

    override fun isFullScreen(): Boolean {
        //是否沉浸式， 默认非沉浸式
        return false
    }

    public override fun initCustomerStatusManager() {

    }

    override fun setContentViewId(): Int {
        return R.layout.activity_search
    }

    override fun createPresenter() {
        mPresenter = PSearchImpl(mContext, this)
    }

    override fun onPause() {
        super.onPause()
        overridePendingTransition(0, 0)
    }

    override fun showLoading() {

    }

    override fun hideLoading() {

    }
}
